//
//  BPStoreDBManager.m
//  BPStoreKit_Example
//
//  Created by 404 on 2020/5/27.
//  Copyright © 2020 404. All rights reserved.
//

#import "BPStoreDBManager.h"
#import "BPFMDBHelper.h"
#import <FMDB/FMDB.h>

static NSString *const kUserName = @"user_id";

static NSString *const BPStoreKit = @"DB";
static NSString *const DBName = @"StoreKitDB.db";

static NSString* const ALL_APPS_TABLE = @"t_all_app_list_table";
static NSString* const SEARCH_APP_TABLE = @"t_search_app_table";

static int const ALL_APPS_TABLE_VERSION = 1;
static int const SEARCH_APP_TABLE_VERSION = 1;


#pragma mark - Path

CG_INLINE NSString*

NSFMDBCachePath() {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return paths.firstObject;
}

CG_INLINE NSString*
NSFMDBFilePath() {
    NSString *docPath = NSFMDBCachePath();
    docPath = [docPath stringByAppendingString:@"/BPStoreKit"];
    if([[NSFileManager defaultManager] fileExistsAtPath:docPath] == NO){
        [[NSFileManager defaultManager] createDirectoryAtPath:docPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return docPath;
}

@implementation BPStoreDBManager

+ (BOOL)openDB{
    
    NSString *dbPath = [self dbPathWithUserID:kUserName];
    
    BOOL result = [BPFMDBHelper openDB:dbPath];
    if (result) {
        [self upgradeTableIfNeed];
        [self createTableIfNeed];
    }
    return result;
}

+ (void)closeDB{
    [BPFMDBHelper closeDB];
}

#pragma mark - private

+ (void)upgradeTableIfNeed {
    if (![BPFMDBHelper isDBOpened]) {
        NSLog(@"db is not open");
        return;
    }
    
    int oldVersion = [BPFMDBHelper versionOfTable:ALL_APPS_TABLE];
    if (oldVersion < ALL_APPS_TABLE_VERSION) {
        [BPFMDBHelper dropTable:ALL_APPS_TABLE];
    }
    oldVersion = [BPFMDBHelper versionOfTable:SEARCH_APP_TABLE];
    if (oldVersion < SEARCH_APP_TABLE_VERSION) {
        [BPFMDBHelper dropTable:SEARCH_APP_TABLE];
    }
}

+ (void)createTableIfNeed{
    if (![BPFMDBHelper isDBOpened]) {
        NSLog(@"db is not open");
        return;
    }

    [BPFMDBHelper updateTable:ALL_APPS_TABLE version:ALL_APPS_TABLE_VERSION transaction:^BOOL(FMDatabase * _Nonnull db) {
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ ("
                         "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                         "app_id TEXT NOT NULL UNIQUE,"
                         "name TEXT,"
                         "ver TEXT"
                         ")",ALL_APPS_TABLE];
        
        BOOL result = [db executeUpdate:sql];
        if (result) {
            sql = [NSString stringWithFormat:@"CREATE INDEX IF NOT EXISTS app_idx ON %@(app_id)",ALL_APPS_TABLE];
            result = [db executeUpdate:sql];
        }
        return result;
    }];
    
    [BPFMDBHelper updateTable:SEARCH_APP_TABLE version:SEARCH_APP_TABLE_VERSION transaction:^BOOL(FMDatabase * _Nonnull db) {
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ ("
                         "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                         "keyword TEXT NOT NULL UNIQUE,"
                         "time TEXT"
                         ")",SEARCH_APP_TABLE];
        
        BOOL result = [db executeUpdate:sql];
        return result;
    }];
    
}

+ (NSString *)dbPathWithUserID:(NSString *)user_id{
    
    NSString *filePath = NSFMDBFilePath();
    NSString *dbPath = [[filePath stringByAppendingPathComponent:user_id] stringByAppendingPathComponent:BPStoreKit];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dbPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:dbPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [dbPath stringByAppendingPathComponent:DBName];
}

+ (BOOL)exitDB{
    NSString *userId = kUserName;
    NSString *dbPath = [self dbPathWithUserID:userId];
    return [[NSFileManager defaultManager] fileExistsAtPath:dbPath];
}

#pragma mark - store app

//+ (void)upDateAllApps:(NSArray<BPSKAppCategoryModel *> *)appCategoryModels{
//
//    if (![BPFMDBHelper isDBOpened]) {
//        XHJLog(@"db is not open")
//        return;
//    }
//    NSArray *apps = [self allAppListWithAppRootTypes:appCategoryModels];
//    if (apps.count == 0) {
//        return;
//    }
//
//    NSString *sql = [NSString stringWithFormat:@"REPLACE INTO %@(app_id, name, ver) VALUES (?, ?, ?)",ALL_APPS_TABLE];
//    [BPFMDBHelper executeTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
//        for (BPSKAppModel *model in apps) {
//            [db executeUpdate:sql withArgumentsInArray:@[model.app_id,
//                                                         model.name,
//                                                         model.ver]];
//        }
//    }];
//}
//
//+ (BOOL)updateAppModel:(BPSKAppModel *)appModel{
//    __block BOOL resutl  = NO;
//    NSString *sql = [NSString stringWithFormat:@"REPLACE INTO %@(app_id, name, ver) VALUES (?, ?, ?)",ALL_APPS_TABLE];
//    [BPFMDBHelper executeTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
//        resutl = [db executeUpdate:sql withArgumentsInArray:@[appModel.app_id,
//                                   appModel.name,
//                                   appModel.ver]];
//    }];
//    return resutl;
//}
//
//+ (BPSKAppModel *)appModelWithAppID:(NSString *)appId{
//    if (![BPFMDBHelper isDBOpened]) {
//        XHJLog(@"db is not open")
//        return nil;
//    }
//    __block BPSKAppModel *appModel = nil;
//    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE app_id = ?",ALL_APPS_TABLE];
//    [BPFMDBHelper executeQuery:sql withArguments:@[appId] syncResult:^(FMResultSet * _Nonnull resultSet) {
//        while ([resultSet next]) {
//            appModel = [self generateAppModelFromFMResultSet:resultSet];
//        }
//    }];
//    return appModel;
//}


#pragma mark - search app

//+ (void)inseartSearchHistoryWithKeyWord:(NSString *)keyWord{
//    if (![BPFMDBHelper isDBOpened]) {
//        NSLog(@"db is not open");
//        return;
//    }
//    NSString *timeSp = [self getNowTimeTimestamp];
//    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (keyword, time) VALUES (?, ?)",SEARCH_APP_TABLE];
//    [BPFMDBHelper executeUpdate:sql withArguments:@[keyWord,
//                                                    timeSp]];
//
//}
//
//+ (BOOL) deleteAllSearchHistory{
//    if (![BPFMDBHelper isDBOpened]) {
//        NSLog(@"db is not open");
//        return NO;
//    }
//    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",SEARCH_APP_TABLE];
//    return [BPFMDBHelper executeUpdate:sql withArguments:nil];
//}

//+ (NSArray<BPSKSearchHistoryModel *> *)allSearchKeyWordHistory{
//    if (![BPFMDBHelper isDBOpened]) {
//        XHJLog(@"db is not open")
//        return nil;
//    }
//    __block NSMutableArray *results = [[NSMutableArray alloc] init];
//    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY time",SEARCH_APP_TABLE];
//    [BPFMDBHelper executeQuery:sql withArguments:nil syncResult:^(FMResultSet * _Nonnull resultSet) {
//        while ([resultSet next]) {
//            BPSKSearchHistoryModel *model = [self generateSearchModelFromFMResultSet:resultSet];
//            [results addObject:model];
//        }
//    }];
//    return results;
//}

#pragma mark - private

/// 遍历 applist 二级结构
/// @param appTypes 根数据
//+ (NSArray<BPSKAppModel*>*)allAppListWithAppRootTypes:(NSArray<BPSKAppCategoryModel *> *)appCategoryModels{
//    NSMutableArray *tempAppsArrayM = [NSMutableArray array];
//    for (BPSKAppCategoryModel *category in appCategoryModels) {
//        for (BPSKAppCategoryModel *subCategory in category.children) {
//            NSArray *apps = [self appsWithRootCategory:subCategory];
//            [tempAppsArrayM addObjectsFromArray:apps];
//        }
//    }
//
//    return tempAppsArrayM;
//}
//
//+ (NSArray<BPSKAppModel*>*)appsWithRootCategory:(BPSKAppCategoryModel*)categoryModel{
//    NSMutableArray *arrayM = [NSMutableArray array];
//    [arrayM addObjectsFromArray:categoryModel.clients];
//    return arrayM;
//}
//
//+ (BPSKAppModel *)generateAppModelFromFMResultSet:(FMResultSet *)resultSet {
//    BPSKAppModel *model = [[BPSKAppModel alloc] init];
//    model.app_id = [resultSet stringForColumn:@"app_id"];
//    model.name = [resultSet stringForColumn:@"name"];
//    model.ver = [resultSet stringForColumn:@"ver"];
//    return model;
//}
//
//+ (BPSKSearchHistoryModel *)generateSearchModelFromFMResultSet:(FMResultSet *)resultSet {
//    BPSKSearchHistoryModel *model = [[BPSKSearchHistoryModel alloc] init];
//    model.text = [resultSet stringForColumn:@"keyword"];
//    model.timestamp = [resultSet stringForColumn:@"time"];
//    return model;
//}
//
//+ (NSString *)getNowTimeTimestamp{
//
//    NSDate *datenow = [NSDate date];
//    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
//
//    return timeSp;
//}
@end
